package com.ruoyi.zsyh.controller;

import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.zsyh.domain.ZsyhUserPartsstore;
import com.ruoyi.zsyh.domain.ZsyhUserRepairstore;
import com.ruoyi.zsyh.service.IZsyhUserPartsstoreService;
import com.ruoyi.zsyh.service.IZsyhUserRepairstoreService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zsyh.domain.ZsyhAgentInfo;
import com.ruoyi.zsyh.service.IZsyhAgentInfoService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 大区会长档案Controller
 * 
 * @author yuexl
 * @date 2021-12-10
 */
@Controller
@RequestMapping("/zsyh/agentinfo")
public class ZsyhAgentInfoController extends BaseController
{
    private String prefix = "zsyh/agentinfo";
    private static final Logger log = LoggerFactory.getLogger(ZsyhAgentInfoController.class);

    class JsonTemp{
        private String name;
        private Object value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }
    }

    @Autowired
    private IZsyhAgentInfoService zsyhAgentInfoService;
    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;
    @Autowired
    private IZsyhUserPartsstoreService zsyhUserPartsstoreService;

    @RequiresPermissions("zsyh:agentinfo:view")
    @GetMapping()
    public String agentinfo()
    {
        return prefix + "/agentinfo";
    }

    @RequiresPermissions("zsyh:agentinfo:view")
    @GetMapping("/report")
    public String report()
    {
        return prefix + "/report";
    }

    @RequiresPermissions("zsyh:factory:edit")
    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("zsyhAgentInfo", zsyhAgentInfoService.selectZsyhAgentInfoById(id));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("zsyh:factory:edit")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(ZsyhAgentInfo zsyhAgentInfo)
    {

        zsyhAgentInfo.setAgentPassword(new Md5Hash(zsyhAgentInfo.getAgentPassword()).toHex());
        int num = zsyhAgentInfoService.updateZsyhAgentInfoApplet(zsyhAgentInfo);
        return toAjax(num);
    }

    /**
     * 查询大区会长档案列表
     */
    @RequiresPermissions("zsyh:agentinfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZsyhAgentInfo zsyhAgentInfo)
    {
        startPage();
        List<ZsyhAgentInfo> list = zsyhAgentInfoService.selectZsyhAgentInfoList(zsyhAgentInfo);
        return getDataTable(list);
    }

    /**
     * 查询大区会长档案列表
     */
    @RequiresPermissions("zsyh:agentinfo:list")
    @PostMapping("/listCount")
    @ResponseBody
    public TableDataInfo listCount()
    {
        startPage();
        List<List<JsonTemp>> resultList = new ArrayList<>();
        //获取会长数据
        ZsyhAgentInfo zsyhAgentInfo = new ZsyhAgentInfo();
        List<ZsyhAgentInfo> list = zsyhAgentInfoService.selectZsyhAgentInfoList(zsyhAgentInfo);
        //获取配件店数据
        List<ZsyhUserPartsstore> zsyhUserPartsstoreList = zsyhUserPartsstoreService.selectZsyhUserPartsstoreList(new ZsyhUserPartsstore());
        //获取师傅数据
        List<ZsyhUserRepairstore> zsyhUserRepairstoreList = zsyhUserRepairstoreService.selectZsyhUserRepairstoreList(new ZsyhUserRepairstore());

        List<JsonTemp> agentData =new ArrayList<>();
        for(int i=0;i<list.size();i++) {
            JsonTemp jsonTemp = new JsonTemp();
            if (list.get(i).getAgentName() == "黑龙江省级会长") {
                jsonTemp.setName(list.get(i).getAgentName().substring(0,3));
                jsonTemp.setValue(1);
            } else {
                jsonTemp.setName(list.get(i).getAgentName().substring(0,2));
                jsonTemp.setValue(1);
            }
            agentData.add(jsonTemp);
        }
        resultList.add(getListData(agentData));

        List<JsonTemp> partsStoreData =new ArrayList<>();
        for(int i=0;i<zsyhUserPartsstoreList.size();i++) {
            JsonTemp jsonTemp = new JsonTemp();
            if (zsyhUserPartsstoreList.get(i).getStoreProvinceName() == "黑龙江省") {
                jsonTemp.setName(zsyhUserPartsstoreList.get(i).getStoreProvinceName().substring(0,3));
                jsonTemp.setValue(1);
            } else {
                jsonTemp.setName(zsyhUserPartsstoreList.get(i).getStoreProvinceName().substring(0,2));
                jsonTemp.setValue(1);
            }
            partsStoreData.add(jsonTemp);
        }
        resultList.add(getListData(partsStoreData));

        List<JsonTemp> repairStoreData =new ArrayList<>();
        for(int i=0;i<zsyhUserRepairstoreList.size();i++) {
            JsonTemp jsonTemp = new JsonTemp();
            if (zsyhUserRepairstoreList.get(i).getStoreProvinceName() == "黑龙江省") {
                jsonTemp.setName(zsyhUserRepairstoreList.get(i).getStoreProvinceName().substring(0,3));
                jsonTemp.setValue(1);
            } else {
                jsonTemp.setName(zsyhUserRepairstoreList.get(i).getStoreProvinceName().substring(0,2));
                jsonTemp.setValue(1);
            }
            repairStoreData.add(jsonTemp);
        }
        resultList.add(getListData(repairStoreData));

        return getDataTable(resultList);
    }

    public List<JsonTemp> getListData(List<JsonTemp> mapData){
        List<JsonTemp> resultList = new ArrayList<>();
        HashMap<String, Integer> newMap = new HashMap<>();
        for (JsonTemp s1 : mapData) {
            int count = 1;
            if (newMap.containsKey(s1.getName())) {
                int count1 = newMap.get(s1.getName());
                count1++;
                newMap.put(s1.getName(), count1);
            } else {
                newMap.put(s1.getName(), count);
            }
        }
        for (Map.Entry<String, Integer> entry : newMap.entrySet()) {
            JsonTemp jsonTemp =new JsonTemp();
            jsonTemp.setName(entry.getKey());
            jsonTemp.setValue(entry.getValue());
            resultList.add(jsonTemp);
        }
        return resultList;
    }

    /**
     * 导出大区会长档案列表
     */
    @RequiresPermissions("zsyh:agentinfo:export")
    @Log(title = "大区会长档案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZsyhAgentInfo zsyhAgentInfo)
    {
        List<ZsyhAgentInfo> list = zsyhAgentInfoService.selectZsyhAgentInfoList(zsyhAgentInfo);
        ExcelUtil<ZsyhAgentInfo> util = new ExcelUtil<ZsyhAgentInfo>(ZsyhAgentInfo.class);
        return util.exportExcel(list, "大区会长档案数据");
    }

    /**
     * 新增大区会长档案
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存大区会长档案
     */
    @RequiresPermissions("zsyh:agentinfo:add")
    @Log(title = "大区会长档案", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZsyhAgentInfo zsyhAgentInfo)
    {
        zsyhAgentInfo.setAgentPassword(new Md5Hash(zsyhAgentInfo.getAgentPassword()).toHex());
        return toAjax(zsyhAgentInfoService.insertZsyhAgentInfo(zsyhAgentInfo));
    }

    /**
     * 修改大区会长档案
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhAgentInfo zsyhAgentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(id);
        mmap.put("zsyhAgentInfo", zsyhAgentInfo);
        return prefix + "/edit";
    }

    /**
     * 查看会长管辖区域
     */
    @GetMapping("/viewAgentArea/{id}")
    public String viewAgentArea(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("agentId", id);
        return prefix + "/viewAgentArea";
    }

    /**
     * 查看市县管理商
     */
    @GetMapping("/viewRaker/{id}")
    public String viewRaker(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("agentId", id);
        return prefix + "/viewRaker";
    }

    /**
     * 查看区域配件店
     */
    @GetMapping("/viewPartsStore/{id}")
    public String viewPartsStore(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("agentId", id);
        return prefix + "/viewPartsStore";
    }

    /**
     * 查看区域配件店
     */
    @GetMapping("/viewRepairStore/{id}")
    public String viewRepairStore(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("agentId", id);
        return prefix + "/viewRepairStore";
    }

    /**
     * 修改保存大区会长档案
     */
    @RequiresPermissions("zsyh:agentinfo:edit")
    @Log(title = "大区会长档案", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZsyhAgentInfo zsyhAgentInfo)
    {
        return toAjax(zsyhAgentInfoService.updateZsyhAgentInfo(zsyhAgentInfo));
    }

    /**
     * 删除大区会长档案
     */
    @RequiresPermissions("zsyh:agentinfo:remove")
    @Log(title = "大区会长档案", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zsyhAgentInfoService.deleteZsyhAgentInfoByIds(ids));
    }

    /**
     * 修改门头
     */
    @GetMapping("/avatar")
    public String avatar(String agentImage,ModelMap mmap)
    {
        mmap.put("avatar",agentImage);
        return prefix + "/avatar";
    }

    /**
     * 营业执照
     */
    @GetMapping("/avatarLicense")
    public String avatarLicense(String agentLicense,ModelMap mmap)
    {
        mmap.put("avatar",agentLicense);
        return prefix + "/avatarLicense";
    }

    /**
     * 保存门头图片
     */
    @Log(title = "大区会长信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAvatar")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, null);
                return new AjaxResult(AjaxResult.Type.SUCCESS,"上传成功",avatar);
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("上传失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 启用用户
     */
    @RequiresPermissions("zsyh:agentinfo:edit")
    @Log(title = "启用用户", businessType = BusinessType.UPDATE)
    @PostMapping("/openUser")
    @ResponseBody
    public AjaxResult openUser(String agentId)
    {
        ZsyhAgentInfo zsyhAgentInfo = new ZsyhAgentInfo();
        zsyhAgentInfo.setId(agentId);
        zsyhAgentInfo.setAgentValid("1");
        return toAjax(zsyhAgentInfoService.updateZsyhAgentInfoApplet(zsyhAgentInfo));
    }

    /**
     * 禁用用户
     */
    @RequiresPermissions("zsyh:agentinfo:edit")
    @Log(title = "禁用用户", businessType = BusinessType.UPDATE)
    @PostMapping("/closeUser")
    @ResponseBody
    public AjaxResult closeUser(String agentId)
    {
        ZsyhAgentInfo zsyhAgentInfo = new ZsyhAgentInfo();
        zsyhAgentInfo.setId(agentId);
        zsyhAgentInfo.setAgentValid("0");
        return toAjax(zsyhAgentInfoService.updateZsyhAgentInfoApplet(zsyhAgentInfo));
    }

    @Log(title = "绑定业务员", businessType = BusinessType.INSERT)
    @PostMapping("/lockUserOperator")
    @ResponseBody
    public AjaxResult lockUserOperator(String agentId,String operatorId)
    {
        ZsyhAgentInfo zsyhAgentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(agentId);
        zsyhAgentInfo.setUserLock(operatorId);
        return toAjax(zsyhAgentInfoService.updateZsyhAgentInfo(zsyhAgentInfo));
    }

}
